package com.huluobo.kotlindemoim1911a2.contract.contact

import android.util.Log
import com.huluobo.kotlindemoim1911a2.data.ContactListItem
import com.huluobo.kotlindemoim1911a2.db.Contact
import com.huluobo.kotlindemoim1911a2.db.IMDatabase
import com.hyphenate.chat.EMClient
import com.hyphenate.exceptions.HyphenateException
import org.jetbrains.anko.doAsync

/**
 * Created by lc on 2022/10/21.
 */
class ContactPresenter(private val view: ContactContract.View) : ContactContract.Presenter {
    val contactListItems = mutableListOf<ContactListItem>()
    override fun loadContacts() {
        doAsync {
            try {
                contactListItems.clear()
                IMDatabase.instance.deleteAllContacts()
                val userNames = EMClient.getInstance().contactManager().allContactsFromServer

                //根据首字符进行排序
                userNames.sortBy {
                    it[0]//it代表list集合中的一个个的String,[0]就代表String的首字符
                }

                userNames.forEachIndexed { index, it ->
                    //1.当index= 0时,或者对比上一个首字符是否和当前首字符相等
                    val showFirstLetter = index == 0 || it[0] != userNames[index - 1][0]
                    val contactListItem =
                        ContactListItem(it, it[0].uppercaseChar(), showFirstLetter)
                    contactListItems.add(contactListItem)
                    val contact = Contact(mutableMapOf("name" to it))
                    IMDatabase.instance.saveContact(contact)
                }

//                userNames.forEach {
//                    //拿到每一个联系人的对象(名字,首字符,是否显示首字符,是否显示首字符有默认值,所以不用填)
//                    val contactListItem = ContactListItem(it, it[0].uppercaseChar())
//                    contactListItems.add(contactListItem)
//                }

                runOnUIThread {
                    view.onLoadContactsSuccess()
                }
            } catch (e: HyphenateException) {
                runOnUIThread {
                    view.onLoadContactsFailed()
                }
                Log.i("TagA", "读取联系人失败,e:${e.message}")
            }
        }
    }
}